<template>
  <el-card>
    <div class="mb-20px">
      <h4>{{ id === -1 ? '新增' : '编辑' }}</h4>
    </div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="auto"
      v-loading="formLoading"
    >
      <el-form-item label="信息ID" prop="id">
        <el-input :modelValue="formData.id" disabled placeholder="创建后自动生成" />
      </el-form-item>
      <el-form-item label="栏目类型" prop="titleType">
        <el-select v-model="formData.titleType" disabled>
          <el-option label="项目采购商机" :value="0" />
          <el-option label="项目分包商机" :value="1" />
          <el-option label="集中招募商机" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="采购公司" prop="purchasingCompany">
        <el-input v-model="formData.purchasingCompany" placeholder="请输入采购公司" disabled />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请输入排序" type="number" min="0" />
      </el-form-item>
      <el-form-item label="咨询电话" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入咨询电话" />
      </el-form-item>
      <el-form-item label="信息类型" prop="informationType">
        <el-select v-model="formData.informationType" placeholder="请选择">
          <el-option
            v-for="i in infotTypeList"
            :key="i.id"
            :label="i.informationType"
            :value="i.informationType"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="地区" prop="area">
        <el-input v-model="formData.area" placeholder="请输入地区" />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="formData.startTime"
          type="date"
          value-format="x"
          placeholder="选择开始时间"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="formData.endTime"
          type="date"
          value-format="x"
          placeholder="选择结束时间"
        />
      </el-form-item>
      <el-form-item label="需求标签" prop="requirementLabel">
        <div>
          <div class="flex items-center">
            <el-button type="primary" @click="formData.requirementLabel.push('')">新增</el-button>
          </div>
          <div
            v-for="(_, index) in formData.requirementLabel"
            :key="index"
            class="flex items-center mt-10px"
          >
            <el-input
              v-model="formData.requirementLabel[index]"
              class="mr-10px !w-240px"
              placeholder="请输入"
            />
            <Icon
              class="color-red-500 cursor-pointer"
              icon="ep:delete-filled"
              @click="formData.requirementLabel.splice(index, 1)"
            />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="详情" prop="details">
        <Editor v-model="formData.details" placeholder="请输入文字" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-input
          :modelValue="formData.createTime && formatDate(formData.createTime)"
          disabled
          placeholder="创建后自动生成"
        />
      </el-form-item>
    </el-form>
    <div>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button
        @click="
          () => {
            delVisitedView(route)
            $router.back()
          }
        "
        >取 消</el-button
      >
    </div>
  </el-card>
</template>
<script setup lang="ts">
import { PlatformInformationApi, PlatformInformation } from '@/api/biz/platforminformation'
import { formatDate } from '@/utils/formatTime'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { InformationTypeApi } from '@/api/biz/informationtype'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { delVisitedView } = useTagsViewStore()

const route = useRoute()
const router = useRouter()
const id = +route.params.id
const titleType = route.query.type ? +route.query.type : 0
const purchasingCompany = route.query.company as string

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  titleType,
  title: undefined,
  purchasingCompany,
  sort: undefined,
  visitors: undefined,
  collectors: undefined,
  shares: undefined,
  inquiries: undefined,
  status: undefined,
  phone: undefined,
  informationType: undefined,
  startTime: undefined,
  endTime: undefined,
  requirementLabel: [''],
  details: undefined,
  createTime: undefined,
  area: undefined
})
const formRules = reactive({
  titleType: [
    {
      required: true,
      message: '栏目类型不能为空',
      trigger: 'change'
    }
  ],
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  purchasingCompany: [{ required: true, message: '采购公司不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
  phone: [{ required: true, message: '咨询电话不能为空', trigger: 'blur' }],
  details: [{ required: true, message: '详情不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const informationTypes = ['寻源询价储备', '招标采购', '询价采购']

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  getInfoTypeList()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await PlatformInformationApi.getPlatformInformation(id)
      data.requirementLabel = data.requirementLabel?.split(',') || []
      data.informationType = isNaN(data.informationType)
        ? data.informationType
        : informationTypes[data.informationType]
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PlatformInformation
    if (formType.value === 'create') {
      await PlatformInformationApi.createPlatformInformation({
        ...data,
        requirementLabel: data.requirementLabel.toString()
      })
      message.success(t('common.createSuccess'))
    } else {
      await PlatformInformationApi.updatePlatformInformation({
        ...data,
        requirementLabel: data.requirementLabel.toString()
      })
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    router.back()
    delVisitedView(route)
  } finally {
    formLoading.value = false
  }
}

// 获取信息类型
const infotTypeList = ref<any[]>([])
const getInfoTypeList = async () => {
  const data = await InformationTypeApi.getInformationTypePage({
    pageNum: 1,
    pageSize: 100
  })
  infotTypeList.value = data.list
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    titleType,
    title: undefined,
    purchasingCompany,
    sort: undefined,
    visitors: undefined,
    collectors: undefined,
    shares: undefined,
    inquiries: undefined,
    status: undefined,
    phone: undefined,
    informationType: undefined,
    startTime: undefined,
    endTime: undefined,
    requirementLabel: [],
    details: undefined,
    createTime: undefined,
    area: undefined
  }
  formRef.value?.resetFields()
}

open(id === -1 ? 'create' : 'update', id === -1 ? undefined : id)
</script>
